/**
 * Created by ren on 08/04/2017.
 */
'use strict';

import React, {
  Component,
}from 'react';
import {
  View,
  Navigator,
  StatusBar,
} from 'react-native';
import {Container} from 'native-base'

import Order from './Order'
import Account from './Account'
import NavigationDrawer from '../components/NavigationDrawer'
import Person from './Person'
import * as NetService from '../utils/netservice'
import {connect} from 'react-redux'
import {checkLogin} from '../actions'
import * as api from '../utils/api'
import PageUtil from '../utils/PageUtil'
import Login from './Login'
import SplashScreen from 'react-native-splash-screen'
class Home extends Component {
  constructor(props) {
    super(props);
    this.PageUtil = new PageUtil();
    this.state = {
      tabName: 'checkOrder',
      pages: [<NavigationDrawer/>, <Order/>, <Account/>, <Person/>],
      index: 0
    }
  }

  componentWillMount() {
    const {dispatch} =this.props
    storage.load({
      key: 'loginData',
      autoSync: true,
    }).then(ret => {
      let userName = ret.userName;
      let password = ret.password
      if (userName && password) {
        NetService.post(api.login, {
          userName: userName,
          password: password
        }).then(() => {
          SplashScreen.hide();
          dispatch(checkLogin())
        },(err)=>{
          NetService.toast(err.message)
          SplashScreen.hide();
        })
      } else {
        SplashScreen.hide();
        this.PageUtil.resetTo(Login)
      }
    }).catch(err => {
      SplashScreen.hide();
      this.PageUtil.resetTo(Login)
      console.log(err)
    })
  }

  render() {
    const {pages, index} =this.state
    const {loginStatus}=this.props
    if (!loginStatus) {
      return <View/>
    }
    return (
      <Container style={{flex: 1,backgroundColor:'#F4F4F4'}}>
        {pages[index]}
      </Container>
    );
  }
}
function select(store) {
  return {
    loginStatus: store.routesStore.loginStatus
  }
}
export default connect(select)(Home)

